package com.hzz.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.hzz.gulimall.cart.feign.ProductFeignService;
import com.hzz.gulimall.cart.interceptor.CartInterceptor;
import com.hzz.gulimall.cart.service.CartService;
import com.hzz.gulimall.cart.vo.Cart;
import com.hzz.gulimall.cart.vo.CartItem;
import com.hzz.gulimall.cart.vo.SkuInfoVo;
import com.hzz.gulimall.cart.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    ThreadPoolExecutor executor;
    private final static String CART_PREFIX="jiajialemall:cart:";

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String result =(String) cartOps.get(skuId.toString());
        if (StringUtils.isEmpty(result)){
            //添加购物车
            CartItem cartItem = new CartItem();
            //购物车无此商品
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                //1.远程查询当前添加商品的信息
                R skuInfo = productFeignService.getSkuInfo(skuId);
                SkuInfoVo data = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>(){
                });

                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImage(data.getSkuDefaultImg());
                cartItem.setPrice(data.getPrice());
                cartItem.setTitle(data.getSkuTitle());
                cartItem.setSkuId(skuId);
            }, executor);

            //2.远程查询sku的组合信息,//supplyAsync有返回值，runAsync无返回值
            CompletableFuture<Void> getSkuSaleValues = CompletableFuture.runAsync(() -> {
                List<String> values = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(values);
            }, executor);
            //异步编排完成
            CompletableFuture.allOf(getSkuInfoTask,getSkuSaleValues).get();
            String s = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(),s);

            return cartItem;
        }else{
            CartItem cartItem1 ;
            //购物车有这个商品，修改数量即可
            cartItem1= JSON.parseObject(result, CartItem.class);
            cartItem1.setCount(cartItem1.getCount()+num);
            String s1 = JSON.toJSONString(cartItem1);
            cartOps.put(skuId.toString(),s1);
            return cartItem1;
        }
    }

    @Override
    public CartItem getCartItem(Long parseLong) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String result =(String) cartOps.get(parseLong.toString());
        CartItem cartItem = JSON.parseObject(result, CartItem.class);
        return cartItem;
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        // 临时购物车的key
        //1.是登录，还是没登录
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String tempCartKey = CART_PREFIX + userInfoTo.getUserKey();

        if (userInfoTo.getUserId()!=null){
            // 1已登录 对用户的购物车进行操作
            String cartKey = CART_PREFIX + userInfoTo.getUserId();

            // 2如果临时购物车的数据没有进行合并
            List<CartItem> tempItem = getCartItems(tempCartKey);
            if (tempItem!=null){
                //临时购物车有数据 则进行合并
                log.info("\n[" + userInfoTo.getUserName() + "] 的购物车已合并");
                for (CartItem cartItem : tempItem) {
                    addToCart(cartItem.getSkuId(), cartItem.getCount());
                }
                // 3 清空临时购物车,防止重复添加
                clearCart(tempCartKey);
                // 设置为非临时用户
//                userInfoTo.setTempUser(false);
            }
            // 4 获取登录后的购物车数据 [包含合并过来的临时购物车数据]
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);

        }else {
            // 没登录 获取临时购物车的所有购物项
            cart.setItems(getCartItems(tempCartKey));
        }
        return cart;
    }

    @Override
    public void clearCart(String cartkey) {
        stringRedisTemplate.delete(cartkey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        // 获取要选中的购物项 // 信息还是在原来的缓存中，更新即可
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1?true:false);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));

    }

    @Override
    public void changeItemCount(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId()==null){
            return null;
        }else {
            String cartKey=CART_PREFIX+userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            List<CartItem> collect = cartItems.stream().filter(item -> item.getCheck())
                    .map(item->{
                        // todo 更新最新价格
                        R price = productFeignService.getPrice(item.getSkuId());
                        String data = (String)price.get("data");
                        item.setPrice(new BigDecimal(data));
                        return item;
                    })
                    .collect(Collectors.toList());

            return collect ;
        }

    }

    /**
     * 获取购物车所有项
     */
    private List<CartItem> getCartItems(String cartKey){
        BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(cartKey);
        // key不重要，拿到值即可
        List<Object> values = hashOps.values();
        if (values != null && values.size() > 0) {
            List<CartItem> collect = values.stream().
                    map((obj) -> {
                        String str=(String) obj;
                        CartItem cartItem = JSON.parseObject(str, CartItem.class);
                        return cartItem;
                    }).collect(Collectors.toList());

            return collect;
        }
        return null;
    }



    /**
     * 获取到我们要操作的购物车
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        // 1. 这里我们需要知道操作的是离线购物车还是在线购物车
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();

        //登录了
        String cartkey="";
        if (userInfoTo.getUserId()!=null){
            //jiajialemall:cart:1
            cartkey=CART_PREFIX+userInfoTo.getUserId();
        }else {
            cartkey=CART_PREFIX+userInfoTo.getUserKey();
        }
        //购物车的结构是hash,绑定一个hash操作
        BoundHashOperations<String, Object, Object> operations = stringRedisTemplate.boundHashOps(cartkey);
        return operations;
    }




}
